
/*
 * @Author: chengjiang
 * @Date: 2025-07-26 00:08:46
 * @Description:
 */

package breaker

import (
	"context"
	"fmt"
	"sync"

	"github.com/go-kratos/kratos/v2/middleware"
	"github.com/zeromicro/go-zero/core/breaker"
)

type BreakerMiddleware struct {
	failureRate float64
	timeout     string
	breakers    sync.Map // key: 服务名, value: *breaker.Breaker
}

func NewBreakerMiddleware() *BreakerMiddleware {
	return &BreakerMiddleware{
		// failureRate: failureRate,
		// timeout:     timeout,
	}
}

// 获取服务专属熔断器
func (b *BreakerMiddleware) GetBreaker(serviceName string) middleware.Middleware {
	return func(handler middleware.Handler) middleware.Handler {
		return func(ctx context.Context, req interface{}) (interface{}, error) {
			// 获取或创建熔断器
			brk, _ := b.breakers.LoadOrStore(serviceName, func() breaker.Breaker {
				// timeout, _ := time.ParseDuration(b.timeout)
				// return breaker.NewBreaker(
				// 	breaker.WithFailureRate(b.failureRate),
				// 	breaker.WithTimeout(timeout),
				// )
				return breaker.NewBreaker(breaker.WithName(serviceName))
			}())

			// 执行熔断逻辑
			var resp interface{}
			var err error
			brk.(breaker.Breaker).DoWithFallback(
				func() error {
					var e error
					resp, e = handler(ctx, req)
					return e
				},
				func(e error) error {
					return fmt.Errorf("服务 %s 暂时不可用: %v", serviceName, e)
				},
			)
			return resp, err
		}
	}
}
